package com.caiyi.financial.nirvana.sms.controller;

import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.service.SmsCustomerService;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.Constant;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.youyu.common.api.Result;
import com.youyu.common.enums.BaseResultCode;
import com.youyu.common.utils.YyAssert;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 客户管理
 */
@Api(description = "客户管理用户接口")
@RequestMapping("sms/customer")
@RestController
@CrossOrigin
public class CustomerController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SmsCustomerService smsCustomerService;

    @Autowired
    private DefaultKaptcha captchaProducer;

    @ApiOperation(value = "登录信息", notes = "登录详细描述")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query"),
    })
    @PostMapping(value = "/login")
    public Result login(@RequestParam String account, @RequestParam String password, @RequestParam String code) {
        //获取IP
        String ip = CommUtil.getClientIp(request);
        String ipKey = String.format(JedisKey.SMS_COMMON_IP, ip);
        JedisService.expire(ipKey, 60);
        long loginNum = JedisService.incr(ipKey);
        if (loginNum > Constant.LOGIN_NUM) {
            YyAssert.isFalse(true, ReturnCodeEnum.FAILED.code, "请一分钟后再登录！");
        }
        Object codeObj = session.getAttribute(captchaProducer.getConfig().getSessionKey());
        String validateCode = codeObj != null ? codeObj.toString() : null;
        YyAssert.isFalse(!code.equalsIgnoreCase(validateCode), ReturnCodeEnum.FAILED.code, "验证码错误！");
        SmsUser user = smsCustomerService.getSmsUser(account);
        YyAssert.isFalse(user == null, ReturnCodeEnum.FAILED.code, "账号不存在！");
        YyAssert.isFalse(!user.getPassword().equals(password), ReturnCodeEnum.FAILED.code, "密码错误！");
        //登录成功
        JedisService.del(ipKey);
        session.setAttribute(Constant.SESSION_CUSTOMER_USER, user);
        return Result.ok();
    }

    @ApiOperation(value = "重置密码", notes = "重置密码")
    @PostMapping(value = "/resetPwd")
    public Result resetPwd() {
        return Result.ok(smsCustomerService.resetPwd(smsUser.getAccount()));
    }


    @ApiOperation("图片验证码")
    @PostMapping("/getCaptcha")
    public void getCaptcha() throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        //存入Session
        session.setAttribute(captchaProducer.getConfig().getSessionKey(), capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }


    @ApiOperation(value = "获取当前登录用户信息", notes = "获取当前登录用户信息")
    @PostMapping(value = "/getCustomer")
    public Result getCustomer() {
        Result jsonUtil = new Result();
        jsonUtil.setData(smsCustomerService.getSmsUser(smsUser.getAccount()));
        return jsonUtil;
    }


    @ApiOperation(value = "注销", notes = "注销")
    @PostMapping(value = "/loginOut")
    public Result loginOut() {
        session.removeAttribute(Constant.SESSION_CUSTOMER_USER);
        return new Result();
    }


    @ApiOperation(value = "个性化设置", notes = "个性化设置")
    @PostMapping("/updateSmsUser")
    public Result updateSmsUser(@RequestBody @ApiParam(name = "user", value = "客户参数实体", required = true) SmsUser user) {
        SmsUser userTemp = new SmsUser();
        BeanUtils.copyProperties(smsUser, userTemp);
        userTemp.setIp(user.getIp());
        userTemp.setReceiveUrl(user.getReceiveUrl());
        userTemp.setRemindValue(user.getRemindValue());
        userTemp.setRemindPhone(user.getRemindPhone());
        Result jsonUtil = Result.ok(smsCustomerService.updateSmsUser(userTemp));
        if (jsonUtil.getCode().equals(BaseResultCode.SUCCESS.getCode())) {
            session.setAttribute(Constant.SESSION_CUSTOMER_USER, userTemp);
            jsonUtil.setData(userTemp);
        }
        return jsonUtil;
    }


    @ApiOperation(value = "首页", notes = "首页")
    @PostMapping("/index")
    public Result index() {
        return Result.ok(smsCustomerService.index(smsUser));
    }


}
